package com.example.score.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.score.common.Result;
import com.example.score.dto.SaveSpecialtyLevelDto;
import com.example.score.entity.ClassInfo;
import com.example.score.entity.ExamBase;
import com.example.score.entity.ExamDetail;
import com.example.score.entity.vo.AcademicLevelResult;
import com.example.score.mapper.ClassInfoMapper;
import com.example.score.mapper.ExamBaseMapper;
import com.example.score.mapper.ExamDetailMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/class")
@RequiredArgsConstructor
@Slf4j
public class ClassController {

    private final ExamDetailMapper examDetailMapper;

    private final ClassInfoMapper classInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    public Result<List<ClassInfo>> getClassList(@RequestParam Long examId) {
        try {
            ExamDetail examDetail = examDetailMapper.selectByExamId(examId);
            List<ClassInfo> classList = classInfoMapper.selectByExamDetailId(examDetail.getId());
            return Result.success(classList);
        } catch (Exception e) {
            log.error("获取班级列表失败: {}", e.getMessage(), e);
            return Result.error("获取班级列表失败");
        }
    }

    @GetMapping("/get/{examId}")
    public Result<ClassInfo> getStatus(@PathVariable Long examId,
                                             @RequestParam(required = false) Long classId) {
        try {
            ExamDetail examDetail = examDetailMapper.selectByExamId(examId);
            ClassInfo classInfo = classInfoMapper.selectByExamDetailIdAndClassIdId(examDetail.getId(), classId);
            return Result.success(classInfo);
        } catch (Exception e) {
            log.error("获取班级失败: {}", e.getMessage(), e);
            return Result.error("获取班级失败");
        }
    }

    @GetMapping("/get/specialtyLevel")
    public Result<?> getSpecialtyLevel(@RequestParam(required = false) Long teacherId) {
        String specialtyLevelPrefix = "SPECIALTYLEVEL_"+teacherId;
        return Result.success(redisTemplate.opsForValue().get(specialtyLevelPrefix));
    }

    @PostMapping("/save/specialtyLevel")
    public Result<?> saveSpecialtyLevel(@RequestBody SaveSpecialtyLevelDto saveSpecialtyLevelDto) {
        String specialtyLevelPrefix = "SPECIALTYLEVEL_"+saveSpecialtyLevelDto.getTeacherId();
        redisTemplate.opsForValue().set(specialtyLevelPrefix,saveSpecialtyLevelDto.getLevelJson());
        return Result.success(true);
    }
}
